/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UDPFiles;

import Tool.FileCodeMaker;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * UDP数据文件读取类（每个读取500字节数据）
 *
 * @author wcss
 */
public class UDPFileReader {

    private File source;
    private ByteBuffer dataBuffer;
    private FileInputStream fis = null;
    private FileChannel fc = null;
    private String fileCode = "";

    public UDPFileReader(File sour) {
        this.source = sour;
        dataBuffer = ByteBuffer.allocate(500);
        if (source != null && source.exists()) {
            try {
                fileCode = FileCodeMaker.makeFileCode(source);
            } catch (Exception ex) {
                Logger.getLogger(UDPFileReader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * 获取文件长度
     *
     * @return
     */
    public long getLength() {
        return source.length();
    }

    /**
     * 获取文件特征码
     *
     * @return
     * @throws Exception
     */
    public String getFileCode() throws Exception {
        return fileCode;
    }

    /**
     * 打开
     *
     * @throws Exception
     */
    public void open() throws Exception {
        fis = new FileInputStream(source);
        fc = fis.getChannel();
    }

    /**
     * 关闭
     *
     * @throws Exception
     */
    public void close() throws Exception {
        fc.close();
        fis.close();
    }

    /**
     * 读取指定位置的数据每次500字节
     *
     * @param pos
     * @return
     * @throws Exception
     */
    public byte[] readPack(long pos) throws Exception {
        if (fc != null) {
            fc.position(pos);            
            fc.read(dataBuffer);
            dataBuffer.flip();
            byte[] content = new byte[dataBuffer.limit()];
            dataBuffer.get(content);
            dataBuffer.clear();
            return content;
        } else {
            return new byte[0];
        }
    }
}
